package org.example.rabbitmq.product.config.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.example.rabbitmq.common.util.MqUtil;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author hzq
 * @date 2021/11/23 10:12
 */
@Slf4j
@Configuration
public class RabbitmqTemplateConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.SIMPLE);
        connectionFactory.setPublisherReturns(true);
        connectionFactory.addConnectionListener(connection -> log.info("创建连接:{}", connection.toString()));
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(MqUtil.buildCustomConfirmCallback());
        rabbitTemplate.setReturnsCallback(MqUtil.buildCustomReturnsCallback());
        return rabbitTemplate;
    }

}
